import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import store from '../store/index.js'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
    redirect: '/index',
    children: [
      {
        path: 'index',
        name: 'index',
        component: () => import('../views/home/index.vue'),
      },
      {
        path: 'pic',
        name: 'pic',
        component: () => import('../views/home/pic.vue'),
        meta: {
          bread: ['相册管理']
        }
      },
      {
        path: 'userlist',
        name: 'userlist',
        component: () => import('../views/user/list.vue'),
        meta: {
          bread: ['会员列表']
        }
      },
      {
        path: 'setting',
        name: 'setting',
        component: () => import('../views/setting/setting.vue'),
        meta: {
          bread: ['设置', '基本设置']
        }
      },
      {
        path: 'goodslist',
        name: 'goodslist',
        component: () => import('../views/goods/goodslist.vue'),
        meta: {
          bread: ['商品列表']
        }
      },
      {
        path: 'addgoods',
        name: 'addgoods',
        component: () => import('../views/goods/addgoods.vue'),
        meta: {
          bread: ['发布商品']
        }
      },
      {
        path: 'editgoods',
        name: 'editgoods',
        component: () => import('../views/goods/editgoods.vue'),
        meta: {
          bread: ['编辑商品']
        }
      },
      {
        path: 'catelist',
        name: 'catelist',
        component: () => import('../views/goods/catelist.vue'),
        meta: {
          bread: ['分类列表']
        }
      },
    ]
  },
  {
    path: '/about',
    name: 'About',
    component: () => import('../views/About.vue')
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/login.vue')
  },
  {
    path: '/bread',
    name: 'bread',
    component: () => import('../views/bread.vue')
  },
]

const router = new VueRouter({
  routes
})
// 全局守卫
router.beforeEach((to, from, next) => {
  // 判断是管理后台的路由地址 路径是/开头的,找到说明大于-1
  if (to.path.indexOf('/') > -1) {
    // 判断登录页面
    if (to.path == '/login') {  //访问登录页面时
      if (store.state.token != '') { //登录的时候，跳转到首页
        next()
      }
    } else { // 除了登录页面的其他页面
      // 用户没登录的时候
      if (store.state.token == '') {
        next('/login')
      }
    }
    // 路由守卫添加面包屑
    // console.log(to.meta);
    // 判断meta属性 每个路由里都有
    if (to.meta.hasOwnProperty('bread')) { //判断自身有没有面包屑属性
      // 添加面包屑，调用vuex方法
      store.commit('setBread', to.meta.bread)
    } else {
      store.commit('setBread', []) //没有面包屑属性是，传个空
    }
  }
  next()
})
export default router
